package com.inspectortime.webapp;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.inspectortime.domain.type.LockboxType;
import com.inspectortime.util.SpringValidatorUtils;
import com.mkode.util.java.lang.ClassUtils;


/**
 * Validates fields on the "Reserve Time" page of the wizard
 * 
 */
public class InspectionReserveTimeValidator implements Validator {

	private static int LOCKBOX_REALTOR_TYPE_CODE_LENGTH = 7;


	public boolean supports(Class clazz) {
		return ClassUtils.isInstanceOf(clazz, InspectionCriteria.class);
	}

	public void validate(Object obj, Errors errors) {

		InspectionCriteria inspectionCriteria = (InspectionCriteria) obj;
		

		//If either name fields of Second Home Buyer or filled out, validate that the rest of the
		//second home buyer information is filled out
		if (!SpringValidatorUtils.isEmptyOrWhitespace(errors, "secondHomeBuyer.name.first") 
				|| !SpringValidatorUtils.isEmptyOrWhitespace(errors, "secondHomeBuyer.name.last")) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "secondHomeBuyer.name.first", "required");
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "secondHomeBuyer.name.last", "required");
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "secondHomeBuyer.phone", "required");
		}
		
		validateLockboxType(inspectionCriteria.getInspection().getLockboxType(), inspectionCriteria.getInspection().getLockboxRealtorCode(), errors);
		
		if (!SpringValidatorUtils.isEmptyOrWhitespace(errors, "inspection.listingAgentName")) {
			SpringValidatorUtils.rejectIfTooLong(errors, "inspection.listingAgentName", "tooLong", 50);
		}
		
		if (!SpringValidatorUtils.isEmptyOrWhitespace(errors, "inspection.listingAgentPhoneNumber")) {
			SpringValidatorUtils.rejectInvalidPhone(errors, "inspection.listingAgentPhoneNumber");
		}
		
	}
	
	protected void validateLockboxType(LockboxType lockboxType, String realtorCode, Errors errors) {
		
		if (StringUtils.hasText(realtorCode)) {
			if (lockboxType.equals(LockboxType.Contractor)) {
				if (!org.apache.commons.lang.StringUtils.isAlphanumeric(realtorCode)) {
					errors.rejectValue("inspection.lockboxRealtorCode", "invalid.contractortype", null);
				}
			} else if (lockboxType.equals(LockboxType.Realtor)) {
				if (realtorCode.length() != LOCKBOX_REALTOR_TYPE_CODE_LENGTH) {
					errors.rejectValue("inspection.lockboxRealtorCode", "invalid.realtortype", null);
				}
			}
		}
	}
	

}
